<?php
class AccountController extends Zend_Controller_Action
{
	public function init()
	{
		$this->_helper->layout()->setLayout('tmplayout');
	}
    public function logonAction ()
    {
    	if ($this->getRequest()->isPost()) {
    		$data = $this->getRequest()->getPost();
    		$result = $this->logon($data);
    		if ($result->isValid()) {               
                return $this->_helper->redirector('index', 'index');                
            }
    	}
    }
    
    public function logoffAction ()
    {
    	$auth = Zend_Auth::getInstance();
        $auth->clearIdentity();
        $this->_helper->redirector('index', 'index');  
    }
    public function registerAction()
    {
    	if ($this->getRequest()->isPost()) {
    		$db = Zend_Controller_Front::getInstance()->getParam('bootstrap')->getPluginResource('db')->getDbAdapter();
    		$data = $this->getRequest()->getPost();
    		
    		$result = $db->insert('account', $data);
    		if ($result) {
    			$this->logon($data);
    			$this->_helper->redirector('index', 'index');  
    		}    		
    	}
    }
    
    private function logon($data)
    {
    	$db = Zend_Controller_Front::getInstance()->getParam('bootstrap')->getPluginResource('db')->getDbAdapter();
    		$authAdapter = new Zend_Auth_Adapter_DbTable($db);
	        $authAdapter->setTableName('account')
	            ->setIdentityColumn('name')
	            ->setCredentialColumn('password');	            
	        
	        $authAdapter->setIdentity($data['name']);
	        $authAdapter->setCredential($data['password']);
	        $auth = Zend_Auth::getInstance();
	        $result = $auth->authenticate($authAdapter);
	        
	        if ($result->isValid()) 
        	{
            	$data = $authAdapter->getResultRowObject(null, 'password');
            	$auth->getStorage()->write($data);            	
        	}
	        
	       	return $result;
    }
}